<template>
  <!-- 已售统计 -->
  <view class="page-sold tab-bar-page">
    <topBar :tabTitle="`${getLanguageText('当前', AppSetting.language)} 第${AppSetting.periodsNum}期`"/>
    <template v-if="!fullStatus">
      <!-- 期数选择 -->
      <flex class="page-nav">
        <span class="expalin">
          {{ getLanguageText('期数', AppSetting.language) }}：
        </span>
        <uni-data-select
          class="search-input"
          v-model="search.periodsNum"
          :localdata="periodsNumRange"
          placeholder="请选择期数"
          @change="periodsNumChange"
        >
        </uni-data-select>
        <button style="margin: 0 0 0 0.5rem;" type="primary" size="mini" @click="myClick('打印')">
          {{ getLanguageText('打印', AppSetting.language) }}
        </button>
      </flex>
      <flex class="page-nav tab-bar" justify="space-between">
        <flex class="tab-item" justify="center" :class="{ tabselect: tabselect == 1 }" @click.native="tabselect = 1">
          {{ getLanguageText('大票', AppSetting.language) }}
        </flex>
        <flex class="tab-item" justify="center" :class="{ tabselect: tabselect == 2 }" @click.native="tabselect = 2">
          {{ getLanguageText('小票', AppSetting.language) }}
        </flex>
      </flex>
      <flex class="page-nav" justify="space-between">
        <button size="mini" @click="myClick('按数字大小排序')">
          {{ getLanguageText('按数字大小排序', AppSetting.language) }}
        </button>
        <button size="mini" @click="myClick('按节数大小排序')">
          {{ getLanguageText('按节数大小排序', AppSetting.language) }}
        </button>
      </flex>
    </template>
    <view class="page-nav">
      <flex justify="space-between">
        <flex>
          <view class="explain">{{ getLanguageText('当前节数汇总', AppSetting.language) }}：{{ orderNumCollect }}</view>
          <view class="explain">{{ getLanguageText('总金额', AppSetting.language) }}：￥{{ moneyCollect }}</view>
        </flex>
        <button style="margin:0; min-width: 5rem;" size="mini" @click="myClick('全屏')">
          {{ fullStatus ? '退出全屏' : '数据全屏' }}
        </button>
      </flex>
      <flex>
        <flex class="table">
          <view class="explain" v-if="!tableList.length" style="flex:1;text-align:center;">
            {{ '暂无数据' }}
          </view>
          <template v-else>
            <view 
              class="table-nav"
              v-for="(item, index) in tableList" :key="index"
            >
              <flex class="tr header">
                <view class="td" style="padding-left:0.2rem;">{{ getLanguageText('号码', AppSetting.language) }}</view>
                <view class="td" style="padding-left:0.2rem;">{{ getLanguageText('节数', AppSetting.language) }}</view>
              </flex>
              <flex class="tr" v-for="(v, index) in item" :key="index">
                <!-- <view class="td">*{{ `${parseInt(v.orderNum)<10?0:''}${v.orderNum}` }}*</view> -->
                <view class="td">*{{ `${v.orderNum}` }}*</view>
                <view class="td" :style="quantityColor(v.quantity)">{{ v.quantity }}</view>
              </flex>
            </view>
          </template>
        </flex>
      </flex>
    </view>
    <comTabBar v-show="!fullStatus" label="已售" />
    <!-- 蓝牙打印 -->
    <uni-popup ref="bluetoothPrintingPopup" type="bottom" background-color="#fff">
      <bluetoothPrinting ref="bluetoothPrinting" :status="2" :content="printContent" />
    </uni-popup>
  </view>
</template>
<script>
import { 
  getAppSetting,
  getOrderList, 
  getOrderSetting
} from '../../utils/appStorage'
import { getLanguageText } from '../../utils/language'

export default {
  name: "sold",
  data() {
    return {
      AppSetting: {},
      OrderSetting: {},
      OrderStatisticsList: [],
      search: {
        periodsNum: ''
      },
      twoList: [],
      orderList: [],
      lists: [],
      tabselect: 1,
      printContent: '',
      fullStatus: false
    };
  },
  components: {},
  onLoad() {
    for (let i = 0; i < 100; i++) {
      this.twoList.push({
        orderNum: i,
        quantity: 0
      })
    }
    getAppSetting(data => {
      this.AppSetting = data
      this.search.periodsNum = this.AppSetting.periodsNum
      getOrderSetting(data => {
        this.OrderSetting = data
        this.OrderStatisticsInit()
      })
    })
  },
  watch: {
    tabselect() {
      this.twoListInit()
    }
  },
  computed: {
    periodsNumRange() {
      // let rang = [{value: '',text: '全部'}]
      let rang = []
      this.OrderStatisticsList.map(v => {
        rang.push({
          value: v.periodsNum,
          text: `第${v.periodsNum}期`
        })
      })
      return rang
    },

    orderListFilter() {
      if (this.tabselect == 1) {
        return this.orderList.filter(v => v.orderNum.length == 4)
      } else {
        return []
      }
    },

    tableList() {
      let arr = this.tabselect == 1 ? this.orderListFilter : this.twoList
      if (arr && arr.length) {
        let N = parseInt(arr.length / 4)
        return [
          JSON.parse(JSON.stringify(arr)).splice(0, N),
          JSON.parse(JSON.stringify(arr)).splice(N, N),
          JSON.parse(JSON.stringify(arr)).splice(N * 2, N),
          JSON.parse(JSON.stringify(arr)).splice(N * 3, (arr.length - N * 3))
        ]
      }
      return []
    },

    // 当前节数汇总
    orderNumCollect() {
      let arr = this.tabselect == 1 ? this.orderListFilter : this.twoList
      let orderNumCollect = 0
      for (let i = 0; i < arr.length; i++) {
        let item = arr[i]
        orderNumCollect += parseInt(item.quantity)
      }
      return orderNumCollect
    },

    // 总金额
    moneyCollect()  {
      let arr = this.tabselect == 1 ? this.orderListFilter : this.twoList
      let moneyCollect = 0
      for (let i = 0; i < arr.length; i++) {
        let item = arr[i]
        if (item.money) {
          moneyCollect += item.money
        } else {
          moneyCollect += item.quantity * (item.orderNum.length == 4 ? this.OrderSetting.quantityPrice_1 : this.OrderSetting.quantityPrice_2)
        }
      }
      return moneyCollect
    },
  },
  methods: {
    getLanguageText,
    twoListInit() {
      if (this.tabselect == 2) {
        this.twoList = this.twoList.map(v => {
          v.quantity = 0
          return v
        })
        let arr = this.orderList.filter(v => v.orderNum.length == 2)
        for (let i = 0; i < arr.length; i++) {
          const e = arr[i]
          this.twoList[parseInt(e.orderNum)].quantity += e.quantity
        }
      }
    },
    orderListInitSetTime() {
      if (
        this.OrderStatisticsList &&
        this.OrderStatisticsList.length
      ) {
        this.orderListInit()
      } else {
        setTimeout(() => {this.orderListInitSetTime()}, 300)
      }
    },
    // 期数数据初始化
    OrderStatisticsInit() {
      uni.getStorage({
        key: 'OrderStatistics',
        success: (res) => {
          this.OrderStatisticsList = [
            ...this.OrderStatisticsList,
            ...res.data.map(v => {
              return v
            })
          ]
          setTimeout(() => {this.orderListInitSetTime()}, 500)
        }
      })
      // 拼接当前期数数据
      getOrderList(listData => {
        this.OrderStatisticsList.push({
          // 号码维度
          orderList: listData.map(v => {
            return {
              ...v,
              periodsNumStatus: '未开奖',
              periodsNum: this.AppSetting.periodsNum
            }
          }),
          periodsNum: this.AppSetting.periodsNum,
          drawingDate: this.OrderSetting.drawingDate,
          orderAmount: ''
        })
      })
    },

    periodsNumChange(v) {
      this.search.periodsNum = v
      this.orderListInit()
    },

    orderListInit() {
      let list = []
      this.OrderStatisticsList.map(orderStatistics => {
        if (
          !this.search.periodsNum || 
          this.search.periodsNum === orderStatistics.periodsNum
        ) {
          let arr = [
            ...list,
            ...orderStatistics.orderList.filter(v => !v.del)
          ]
          for (let key = 0; key < arr.length; key++) {
            const e = arr[key];
            // e.orderNum e.quantity
            let index = 0
            if (list.filter((v, i) => {
              if (v.orderNum == e.orderNum) {
                index = i
                return true
              }
            }).length) {
              list[index].quantity += e.quantity
            } else {
              list.push(e)
            }
          }
        }
      })
      this.orderList = list
      this.twoListInit()
    },

    quantityColor(data) {
      if (data >= 300) return { background: '#ff1515', color: '#fff' }
      if (data >= 200) return { background: '#d9ba0c', color: '#fff' }
      if (data >= 100) return { background: '#21a437', color: '#fff' }
      return {}
    },

    myClick(type, data) {
      let listArr = this.tabselect == 1 ? this.orderList : this.twoList
      switch (type) {
        case '全屏':
          this.fullStatus = !this.fullStatus
          break;
        case '按数字大小排序':
          console.log('按数字大小排序---------')
          listArr.sort(function(a, b){
            return parseInt(b.orderNum) - parseInt(a.orderNum)
          })
          break;
        case '按节数大小排序':
          listArr.sort(function(a, b){
            return parseInt(b.quantity) - parseInt(a.quantity)
          })
          break;
        case '打印':
          this.printContent = '\r\n\r\n\r\n----------------------------\r\n\r\n\r\n已售统计：\r\n\r\n\r\n'
          let arr = this.tabselect == 1 ? this.orderListFilter : this.twoList
          let total = 0
          for (let index = 0; index < arr.length; index++) {
            const item = arr[index]
            if(item.quantity) {
              let money = item.quantity * (item.orderNum.length == 4 ? this.OrderSetting.quantityPrice_1 : this.OrderSetting.quantityPrice_2)
              total += money
              this.printContent += `\r\n\r\nNo:${item.orderNum}     ${item.quantity}      ￥${money}`
            }
          }
          this.printContent += `\r\n\r\n\r\n Toatal:   ￥${total}\r\n\r\n\r\n----------------------------\r\n\r\n\r\n`
          // console.log('printContent----')
          console.log(this.printContent)
          this.$refs.bluetoothPrintingPopup.open()
          setTimeout(() => {
            this.$refs.bluetoothPrinting.blueadapterCheck()
          }, 500)
          break;
        case '订单详情':
          this.lists.forEach(e => {
            if (e.id == data.id) {
              if (e.del) {
                uni.showToast({title: "数据已作废", icon: 'error'})
                return
              }
              uni.navigateTo({
                url: '/pages/orderDetail/orderDetail?query=' + encodeURIComponent(JSON.stringify(e))
              })
            }
          })
          break;
        default:
          break;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.page-sold {
  .expalin {
    font-size: 0.7rem;
    color: #747474;
  }
  .tab-bar {
    padding: 0.1rem 2.5rem 0.2rem;
    width: calc(100% - 5rem);
    font-size: 0.6rem;
    .tab-item {
      width: 3rem;
      text-align: center;
      line-height: 1.6rem;
      border-bottom: 0.2rem solid #fff;
      &.tabselect {
        border-bottom: 0.2rem solid #409EFF;
      }
    }
  }
  .explain {
    margin-right: 0.8rem;
    font-size: 0.5rem;
    color: #626262;
  }
  .table {
    width: 100%;
    margin-top: 0.5rem;
    display: flex;
    justify-content: space-between;
    align-items: flex-start !important;
    font-size: 0.7rem;
    .table-nav {
      flex: 1;
      .tr {
        border: 1px solid #ececec;
        &.header {
          background: #409EFF;
          color: #fff;
          border-top: 1px solid #409EFF;
          border-bottom: 1px solid #409EFF;
        }
        .td {
          padding: 0.1rem 0rem;
          flex: 1;
          font-weight: bold;
          max-width: 42px;
          text-align: center;
        }
        .td + .td {
          border-left: 1px solid #ececec;
        }
      }
    }
  }
}
</style>
